package net.lab1024.sa.admin.module.business.template.service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import jakarta.validation.Valid;
import net.lab1024.sa.admin.module.business.template.constant.QuotationTypeEnum;
import net.lab1024.sa.admin.module.business.template.dao.QuotationTemplateDao;
import net.lab1024.sa.admin.module.business.template.dao.QuotationTemplateItemsDao;
import net.lab1024.sa.admin.module.business.template.domain.entity.QuotationTemplateEntity;
import net.lab1024.sa.admin.module.business.template.domain.entity.QuotationTemplateItemsEntity;
import net.lab1024.sa.admin.module.business.template.domain.form.QuotationTemplateAddForm;
import net.lab1024.sa.admin.module.business.template.domain.form.QuotationTemplateQueryForm;
import net.lab1024.sa.admin.module.business.template.domain.form.QuotationTemplateUpdateForm;
import net.lab1024.sa.admin.module.business.template.domain.vo.QuotationTemplateDetailVO;
import net.lab1024.sa.admin.module.business.template.domain.vo.QuotationTemplateItemsVO;
import net.lab1024.sa.admin.module.business.template.domain.vo.QuotationTemplateVO;
import net.lab1024.sa.base.common.code.UserErrorCode;
import net.lab1024.sa.base.common.domain.RequestUser;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.domain.PageResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.lab1024.sa.base.common.util.SmartRequestUtil;
import net.lab1024.sa.base.module.support.datatracer.constant.DataTracerTypeEnum;
import net.lab1024.sa.base.module.support.datatracer.service.DataTracerService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

/**
 * 报价单模版 Service
 *
 * @Author zzx
 * @Date 2025-08-06 11:03:50
 * @Copyright zzx
 */

@Service
public class QuotationTemplateService {

    @Resource
    private QuotationTemplateDao quotationTemplateDao;

    @Resource
    private QuotationTemplateItemsDao quotationTemplateItemsDao;

    @Resource
    private DataTracerService dataTracerService;

    /**
     * 分页查询
     */
    public PageResult<QuotationTemplateVO> queryPage(QuotationTemplateQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<QuotationTemplateVO> list = quotationTemplateDao.queryPage(page, queryForm);
        return SmartPageUtil.convert2PageResult(page, list);
    }

    /**
     * 查询所有模板
     */
    public List<QuotationTemplateVO> queryAll(QuotationTemplateEntity queryForm) {
        return quotationTemplateDao.queryAll(queryForm);
    }

    /**
     * 添加
     */
    public ResponseDTO<String> add(QuotationTemplateAddForm addForm) {
        QuotationTemplateEntity entity = SmartBeanUtil.copy(addForm, QuotationTemplateEntity.class);
        RequestUser user = SmartRequestUtil.getRequestUser();
        entity.setCreateUserId(user.getUserId());
        entity.setUpdateUserId(user.getUserId());
        quotationTemplateDao.insert(entity);
        dataTracerService.insert(entity.getTemplateId(), DataTracerTypeEnum.TEMPLATE);
        return ResponseDTO.ok();
    }

    /**
     * 更新
     *
     */
    public ResponseDTO<String> update(QuotationTemplateUpdateForm updateForm) {
        Long userId = SmartRequestUtil.getRequestUserId();
        QuotationTemplateEntity old = quotationTemplateDao.selectById(updateForm.getTemplateId());
        if (old == null) { return ResponseDTO.error(UserErrorCode.DATA_EMPTY, "模版不存在，请检查"); }
        QuotationTemplateEntity quotationTemplateEntity = SmartBeanUtil.copy(updateForm, QuotationTemplateEntity.class);
        quotationTemplateEntity.setUpdateUserId(userId);
        quotationTemplateDao.updateById(quotationTemplateEntity);
        dataTracerService.update(updateForm.getTemplateId(), DataTracerTypeEnum.TEMPLATE, old, quotationTemplateEntity);
        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     */
    public ResponseDTO<String> batchDelete(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)){
            return ResponseDTO.ok();
        }

        quotationTemplateDao.batchUpdateDeleted(idList, true);
        return ResponseDTO.ok();
    }

    /**
     * 单个删除
     */
    public ResponseDTO<String> delete(Long templateId) {
        if (null == templateId){
            return ResponseDTO.ok();
        }
        quotationTemplateDao.updateDeleted(templateId, true);
        return ResponseDTO.ok();
    }

    public ResponseDTO<List<QuotationTemplateItemsVO>> queryItemsById(@Valid Long templateId) {
        QuotationTemplateDetailVO vo = new QuotationTemplateDetailVO();
        List<QuotationTemplateItemsVO> items = quotationTemplateDao.queryItemsByTempLateId(templateId);
        if (items.isEmpty()) {
            items.addAll(generateItems(templateId));
        }
        return ResponseDTO.ok(items);
    }

    // 生成默认明细
    private List<QuotationTemplateItemsVO> generateItems(Long templateId) {
        List<QuotationTemplateItemsVO> items = new ArrayList<>();
        items.add(new QuotationTemplateItemsVO(templateId, "主材1", "规格1", QuotationTypeEnum.MAIN_MATERIALS.getValue()));
        items.add(new QuotationTemplateItemsVO(templateId, "主材2", "规格2", QuotationTypeEnum.MAIN_MATERIALS.getValue()));
        items.add(new QuotationTemplateItemsVO(templateId, "损耗", "", QuotationTypeEnum.LOSS.getValue()));
        items.add(new QuotationTemplateItemsVO(templateId, "配件1", "规格1", QuotationTypeEnum.ACCESSORY.getValue()));
        items.add(new QuotationTemplateItemsVO(templateId, "配件2", "规格2", QuotationTypeEnum.ACCESSORY.getValue()));
        items.add(new QuotationTemplateItemsVO(templateId, "主材合计", "元", QuotationTypeEnum.SUM_MAIN_MATERIALS.getValue()));
        items.add(new QuotationTemplateItemsVO(templateId, "主材单价", "元/米", QuotationTypeEnum.UNIT_MAIN_MATERIALS.getValue()));
        items.add(new QuotationTemplateItemsVO(templateId, "制作费", "元/米", QuotationTypeEnum.PRODUCE_COST.getValue()));
        items.add(new QuotationTemplateItemsVO(templateId, "喷涂", "元/米", QuotationTypeEnum.SPRAY.getValue()));
        items.add(new QuotationTemplateItemsVO(templateId, "辅材", "元/米", QuotationTypeEnum.AUXILIARY_MATERIALS.getValue()));
        items.add(new QuotationTemplateItemsVO(templateId, "运输", "元/米", QuotationTypeEnum.TRANSPORT.getValue()));
        items.add(new QuotationTemplateItemsVO(templateId, "安装", "元/米", QuotationTypeEnum.INSTALL.getValue()));
        items.add(new QuotationTemplateItemsVO(templateId, "利润", "元/米", QuotationTypeEnum.PROFIT.getValue()));
        items.add(new QuotationTemplateItemsVO(templateId, "出厂单价", "元/米", QuotationTypeEnum.FACTORY_UNIT_PRICE.getValue()));
        items.add(new QuotationTemplateItemsVO(templateId, "税金", "元/米", QuotationTypeEnum.TAXES.getValue()));
        items.add(new QuotationTemplateItemsVO(templateId, "综合单价", "元/米", QuotationTypeEnum.COMPREHENSIVE_UNIT_PRICE.getValue()));
        return items;
    }

    // 添加/更新
    public ResponseDTO<String> addOrUpdate(QuotationTemplateDetailVO detailVO) {
        RequestUser user = SmartRequestUtil.getRequestUser();
        QuotationTemplateEntity templateEntity = SmartBeanUtil.copy(detailVO, QuotationTemplateEntity.class);
        for (int i = 0; i < detailVO.getList().size(); i++) {
            detailVO.getList().get(i).setSerialNumber(i+1);
        }
        templateEntity.setUpdateUserId(user.getUserId());
        quotationTemplateDao.updateById(templateEntity);
        List<QuotationTemplateItemsVO> oldEntities = quotationTemplateDao.queryItemsByTempLateId(detailVO.getTemplateId());
        List<QuotationTemplateItemsEntity> newEntities = SmartBeanUtil.copyList(
                detailVO.getList().stream().filter(item -> item.getTemplateOrderId() == null).toList(),
                QuotationTemplateItemsEntity.class
        );
        List<QuotationTemplateItemsEntity> updateEntities = SmartBeanUtil.copyList(
                detailVO.getList().stream().filter(item -> item.getTemplateOrderId() != null).toList(),
                QuotationTemplateItemsEntity.class
        );
        if (!newEntities.isEmpty()) {
            newEntities.forEach(item -> {
                item.setCreateUserId(user.getUserId());
                item.setUpdateUserId(user.getUserId());
                quotationTemplateItemsDao.insert(item);
                dataTracerService.insert(item.getTemplateOrderId(), DataTracerTypeEnum.TEMPLATE_ITEM);
            });
        }
        if (!oldEntities.isEmpty()) {
            Map<Long, QuotationTemplateItemsEntity> map = updateEntities.stream().collect(Collectors.toMap(QuotationTemplateItemsEntity::getTemplateOrderId, item -> item));
            oldEntities.forEach(old -> {
                QuotationTemplateItemsEntity update = map.get(old.getTemplateOrderId());
                if (update == null) { // 删除
                    update = SmartBeanUtil.copy(old, QuotationTemplateItemsEntity.class);
                    update.setDeletedFlag(1);
                }
                update.setUpdateUserId(user.getUserId());
                quotationTemplateItemsDao.updateById(update);
                dataTracerService.update(update.getTemplateOrderId(), DataTracerTypeEnum.TEMPLATE_ITEM,
                        SmartBeanUtil.copy(old, QuotationTemplateItemsEntity.class), update);
            });
        }
        return ResponseDTO.ok();
    }
}
